<template>
  <el-dialog
    :model-value="visible"
    title="工单详情"
    width="80%"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:visible', $event)"
  >
    <div v-if="ticket" class="ticket-detail">
      <!-- 工单基本信息 -->
      <el-card class="ticket-info-card">
        <template #header>
          <div class="card-header">
            <h3>工单 #{{ ticket.id }}</h3>
            <div class="ticket-status">
              <el-tag :type="getStatusType(ticket.status)" size="large">
                {{ translateStatus(ticket.status) }}
              </el-tag>
            </div>
          </div>
        </template>
        
        <div class="ticket-basic-info">
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="info-item">
                <label>标题：</label>
                <span>{{ ticket.title }}</span>
              </div>
              <div class="info-item">
                <label>优先级：</label>
                <el-tag :type="getPriorityType(ticket.priority)" size="small">
                  {{ translatePriority(ticket.priority) }}
                </el-tag>
              </div>
              <div class="info-item">
                <label>分类：</label>
                <span>{{ translateCategory(ticket.category) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>负责人：</label>
                <span>{{ ticket.assigneeName || '未分配' }}</span>
              </div>
              <div class="info-item">
                <label>创建时间：</label>
                <span>{{ formatDate(ticket.createdAt) }}</span>
              </div>
              <div class="info-item">
                <label>更新时间：</label>
                <span>{{ formatDate(ticket.updatedAt) }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <div class="ticket-description">
          <label>描述：</label>
          <div class="description-content">{{ ticket.description }}</div>
        </div>
      </el-card>

      <!-- 操作区域 -->
      <el-card class="ticket-actions-card">
        <template #header>
          <h4>操作</h4>
        </template>
        
        <div class="action-buttons">
          <el-button type="primary" @click="showUpdateStatusDialog">
            <el-icon><Edit /></el-icon>
            更新状态
          </el-button>
          <el-button type="success" @click="showAssignDialog">
            <el-icon><User /></el-icon>
            指派工单
          </el-button>
          <el-button @click="showAddCommentDialog">
            <el-icon><ChatDotRound /></el-icon>
            添加评论
          </el-button>
          <el-button @click="showAddAttachmentDialog">
            <el-icon><Paperclip /></el-icon>
            添加附件
          </el-button>
        </div>
      </el-card>

      <!-- 评论区域 -->
      <el-card class="comments-card">
        <template #header>
          <h4>评论记录</h4>
        </template>
        
        <div class="comments-list">
          <div
            v-for="comment in ticket.comments || []"
            :key="comment.id"
            class="comment-item"
          >
            <div class="comment-header">
              <div class="comment-author">
                <el-avatar :size="32">{{ comment.authorName?.charAt(0) }}</el-avatar>
                <div class="author-info">
                  <div class="author-name">{{ comment.authorName }}</div>
                  <div class="comment-time">{{ formatDate(comment.createdAt) }}</div>
                </div>
              </div>
              <el-tag v-if="comment.isInternal" type="warning" size="small">内部</el-tag>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
          </div>
          
          <div v-if="!ticket.comments || ticket.comments.length === 0" class="no-comments">
            <el-empty description="暂无评论" />
          </div>
        </div>
      </el-card>

      <!-- 附件区域 -->
      <el-card class="attachments-card">
        <template #header>
          <h4>附件</h4>
        </template>
        
        <div class="attachments-list">
          <div
            v-for="attachment in ticket.attachments || []"
            :key="attachment.id"
            class="attachment-item"
          >
            <div class="attachment-info">
              <el-icon class="attachment-icon"><Document /></el-icon>
              <div class="attachment-details">
                <div class="attachment-name">{{ attachment.fileName }}</div>
                <div class="attachment-meta">
                  {{ formatFileSize(attachment.fileSize) }} • {{ attachment.uploaderName }}
                </div>
              </div>
            </div>
            <div class="attachment-actions">
              <el-button size="small" @click="downloadAttachment(attachment)">
                <el-icon><Download /></el-icon>
                下载
              </el-button>
            </div>
          </div>
          
          <div v-if="!ticket.attachments || ticket.attachments.length === 0" class="no-attachments">
            <el-empty description="暂无附件" />
          </div>
        </div>
      </el-card>

      <!-- 历史记录 -->
      <el-card class="history-card">
        <template #header>
          <h4>操作历史</h4>
        </template>
        
        <el-timeline>
          <el-timeline-item
            v-for="(history, index) in ticket.history || []"
            :key="index"
            :timestamp="formatDate(history.createdAt)"
            :type="getHistoryType(history.action)"
          >
            <div class="history-content">
              <div class="history-action">{{ translateHistoryAction(history.action) }}</div>
              <div class="history-details">{{ history.details }}</div>
              <div class="history-user">{{ history.userName }}</div>
            </div>
          </el-timeline-item>
        </el-timeline>
        
        <div v-if="!ticket.history || ticket.history.length === 0" class="no-history">
          <el-empty description="暂无操作历史" />
        </div>
      </el-card>
    </div>

    <!-- 更新状态对话框 -->
    <el-dialog
      v-model="updateStatusDialog.visible"
      title="更新状态"
      width="500px"
    >
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="新状态">
          <el-select v-model="statusForm.status" placeholder="请选择状态">
            <el-option label="待处理" value="OPEN" />
            <el-option label="处理中" value="IN_PROGRESS" />
            <el-option label="挂起" value="PENDING" />
            <el-option label="已解决" value="RESOLVED" />
            <el-option label="已关闭" value="CLOSED" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="statusForm.note"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updateStatusDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="updating" @click="updateStatus">确认</el-button>
      </template>
    </el-dialog>

    <!-- 指派工单对话框 -->
    <el-dialog
      v-model="assignDialog.visible"
      title="指派工单"
      width="500px"
    >
      <el-form :model="assignForm" label-width="80px">
        <el-form-item label="负责人">
          <el-select v-model="assignForm.assigneeId" placeholder="请选择负责人">
            <el-option
              v-for="agent in agents"
              :key="agent.id"
              :label="agent.name"
              :value="agent.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="assignForm.note"
            type="textarea"
            :rows="3"
            placeholder="请输入指派备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="assigning" @click="assignTicket">确认</el-button>
      </template>
    </el-dialog>

    <!-- 添加评论对话框 -->
    <el-dialog
      v-model="commentDialog.visible"
      title="添加评论"
      width="600px"
    >
      <el-form :model="commentForm" label-width="80px">
        <el-form-item label="评论内容">
          <el-input
            v-model="commentForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入评论内容"
          />
        </el-form-item>
        <el-form-item label="评论类型">
          <el-radio-group v-model="commentForm.isInternal">
            <el-radio :label="false">公开评论</el-radio>
            <el-radio :label="true">内部评论</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="commentDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="addingComment" @click="addComment">确认</el-button>
      </template>
    </el-dialog>

    <!-- 添加附件对话框 -->
    <el-dialog
      v-model="attachmentDialog.visible"
      title="添加附件"
      width="500px"
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        drag
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 jpg/png/gif/pdf/doc/docx 文件，且不超过 10MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="attachmentDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="addingAttachment" @click="addAttachment">确认</el-button>
      </template>
    </el-dialog>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">关闭</el-button>
        <el-button type="primary" @click="editTicket">编辑工单</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useTicketsStore } from '../store/tickets'
import { useUserStore } from '../store/user'
import { ElMessage } from 'element-plus'
import {
  Edit, User, ChatDotRound, Paperclip, Document, Download, UploadFilled
} from '@element-plus/icons-vue'

export default {
  name: 'TicketDetailDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    ticket: {
      type: Object,
      default: null
    }
  },
  emits: ['update:visible', 'update'],
  setup(props, { emit }) {
    const ticketsStore = useTicketsStore()
    const userStore = useUserStore()

    // 对话框状态
    const updateStatusDialog = ref({ visible: false })
    const assignDialog = ref({ visible: false })
    const commentDialog = ref({ visible: false })
    const attachmentDialog = ref({ visible: false })

    // 加载状态
    const updating = ref(false)
    const assigning = ref(false)
    const addingComment = ref(false)
    const addingAttachment = ref(false)

    // 表单数据
    const statusForm = reactive({
      status: '',
      note: ''
    })

    const assignForm = reactive({
      assigneeId: '',
      note: ''
    })

    const commentForm = reactive({
      content: '',
      isInternal: false
    })

    // 文件上传
    const uploadRef = ref()
    const fileList = ref([])

    // 计算属性
    const agents = computed(() => userStore.agents)

    // 方法
    const showUpdateStatusDialog = () => {
      statusForm.status = props.ticket?.status || ''
      statusForm.note = ''
      updateStatusDialog.value.visible = true
    }

    const showAssignDialog = () => {
      assignForm.assigneeId = props.ticket?.assigneeId || ''
      assignForm.note = ''
      assignDialog.value.visible = true
    }

    const showAddCommentDialog = () => {
      commentForm.content = ''
      commentForm.isInternal = false
      commentDialog.value.visible = true
    }

    const showAddAttachmentDialog = () => {
      fileList.value = []
      attachmentDialog.value.visible = true
    }

    const updateStatus = async () => {
      try {
        updating.value = true
        const result = await ticketsStore.updateTicket(props.ticket.id, {
          status: statusForm.status,
          note: statusForm.note
        })
        
        if (result.success) {
          ElMessage.success('状态更新成功')
          updateStatusDialog.value.visible = false
          emit('update')
        } else {
          ElMessage.error(result.message)
        }
      } catch (error) {
        ElMessage.error('状态更新失败')
      } finally {
        updating.value = false
      }
    }

    const assignTicket = async () => {
      try {
        assigning.value = true
        const agent = agents.value.find(a => a.id === assignForm.assigneeId)
        if (!agent) {
          ElMessage.error('请选择负责人')
          return
        }

        const result = await ticketsStore.assignTicket(props.ticket.id, agent)
        
        if (result.success) {
          ElMessage.success('工单指派成功')
          assignDialog.value.visible = false
          emit('update')
        } else {
          ElMessage.error(result.message)
        }
      } catch (error) {
        ElMessage.error('工单指派失败')
      } finally {
        assigning.value = false
      }
    }

    const addComment = async () => {
      try {
        addingComment.value = true
        const result = await ticketsStore.addComment(props.ticket.id, commentForm)
        
        if (result.success) {
          ElMessage.success('评论添加成功')
          commentDialog.value.visible = false
          emit('update')
        } else {
          ElMessage.error(result.message)
        }
      } catch (error) {
        ElMessage.error('评论添加失败')
      } finally {
        addingComment.value = false
      }
    }

    const handleFileChange = (file, files) => {
      fileList.value = files
    }

    const addAttachment = async () => {
      try {
        addingAttachment.value = true
        
        for (const file of fileList.value) {
          const result = await ticketsStore.addAttachment(props.ticket.id, file.raw)
          if (!result.success) {
            ElMessage.error(`文件 ${file.name} 上传失败`)
            return
          }
        }
        
        ElMessage.success('附件添加成功')
        attachmentDialog.value.visible = false
        emit('update')
      } catch (error) {
        ElMessage.error('附件添加失败')
      } finally {
        addingAttachment.value = false
      }
    }

    const downloadAttachment = (attachment) => {
      if (attachment.downloadUrl) {
        const link = document.createElement('a')
        link.href = attachment.downloadUrl
        link.download = attachment.fileName
        link.click()
      }
    }

    const editTicket = () => {
      // 跳转到编辑页面或打开编辑对话框
      emit('update:visible', false)
      // 这里可以触发编辑事件
    }

    // 工具方法
    const getStatusType = (status) => {
      const types = {
        OPEN: 'warning',
        IN_PROGRESS: 'primary',
        PENDING: 'info',
        RESOLVED: 'success',
        CLOSED: 'info'
      }
      return types[status] || 'info'
    }

    const getPriorityType = (priority) => {
      const types = {
        HIGH: 'danger',
        MEDIUM: 'warning',
        LOW: 'success'
      }
      return types[priority] || 'info'
    }

    const getHistoryType = (action) => {
      const types = {
        CREATE: 'primary',
        UPDATE: 'warning',
        ASSIGN: 'success',
        RESOLVE: 'success',
        CLOSE: 'info'
      }
      return types[action] || 'info'
    }

    const translateStatus = (status) => {
      const statusMap = {
        OPEN: '待处理',
        IN_PROGRESS: '处理中',
        PENDING: '挂起',
        RESOLVED: '已解决',
        CLOSED: '已关闭'
      }
      return statusMap[status] || status
    }

    const translatePriority = (priority) => {
      const priorityMap = {
        HIGH: '高',
        MEDIUM: '中',
        LOW: '低'
      }
      return priorityMap[priority] || priority
    }

    const translateCategory = (category) => {
      const categoryMap = {
        technical: '技术问题',
        feature: '功能请求',
        bug: 'Bug报告',
        other: '其他'
      }
      return categoryMap[category] || category
    }

    const translateHistoryAction = (action) => {
      const actionMap = {
        CREATE: '创建工单',
        UPDATE: '更新工单',
        ASSIGN: '指派工单',
        RESOLVE: '解决工单',
        CLOSE: '关闭工单'
      }
      return actionMap[action] || action
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    const formatFileSize = (bytes) => {
      if (!bytes) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    return {
      updateStatusDialog,
      assignDialog,
      commentDialog,
      attachmentDialog,
      updating,
      assigning,
      addingComment,
      addingAttachment,
      statusForm,
      assignForm,
      commentForm,
      uploadRef,
      fileList,
      agents,
      showUpdateStatusDialog,
      showAssignDialog,
      showAddCommentDialog,
      showAddAttachmentDialog,
      updateStatus,
      assignTicket,
      addComment,
      handleFileChange,
      addAttachment,
      downloadAttachment,
      editTicket,
      getStatusType,
      getPriorityType,
      getHistoryType,
      translateStatus,
      translatePriority,
      translateCategory,
      translateHistoryAction,
      formatDate,
      formatFileSize,
      Edit,
      User,
      ChatDotRound,
      Paperclip,
      Document,
      Download,
      UploadFilled
    }
  }
}
</script>

<style scoped>
.ticket-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.ticket-info-card,
.ticket-actions-card,
.comments-card,
.attachments-card,
.history-card {
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.ticket-basic-info {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
  min-width: 80px;
}

.ticket-description {
  margin-top: 20px;
}

.ticket-description label {
  font-weight: 500;
  color: #606266;
  display: block;
  margin-bottom: 8px;
}

.description-content {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  line-height: 1.6;
  color: #303133;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.comment-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fafbfc;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-info {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 500;
  color: #303133;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
}

.attachments-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafbfc;
}

.attachment-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.attachment-icon {
  font-size: 24px;
  color: #409eff;
}

.attachment-details {
  display: flex;
  flex-direction: column;
}

.attachment-name {
  font-weight: 500;
  color: #303133;
}

.attachment-meta {
  font-size: 12px;
  color: #909399;
}

.history-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.history-action {
  font-weight: 500;
  color: #303133;
}

.history-details {
  color: #606266;
}

.history-user {
  font-size: 12px;
  color: #909399;
}

.no-comments,
.no-attachments,
.no-history {
  text-align: center;
  padding: 40px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ticket-basic-info .el-col {
    margin-bottom: 16px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .attachment-item {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .attachment-actions {
    align-self: stretch;
  }
}
</style>